/**
 * Geppetto 前后端联调测试页面
 */

import React, { useState, useEffect } from 'react';
import {
  Box,
  Button,
  Card,
  CardContent,
  Typography,
  Alert,
  CircularProgress,
  Grid,
  Paper,
  Divider,
  List,
  ListItem,
  ListItemText,
  Chip,
} from '@mui/material';
import { useGeppettoWebSocket } from '../hooks/useGeppettoWebSocket';
import { NetworkVisualization } from '../components/Canvas3D';

export const GeppettoTest: React.FC = () => {
  const {
    isConnected,
    isConnecting,
    error,
    networkData,
    simulationData,
    isSimulationRunning,
    connect,
    disconnect,
    initModel,
    getNetwork,
    runSimulation,
    getSimulationData,
    executeCode,
  } = useGeppettoWebSocket();

  const [logs, setLogs] = useState<string[]>([]);
  const [testResults, setTestResults] = useState<Record<string, boolean>>({});

  // 添加日志
  const addLog = (message: string) => {
    const timestamp = new Date().toLocaleTimeString();
    setLogs(prev => [...prev, `[${timestamp}] ${message}`]);
  };

  // 更新测试结果
  const updateTestResult = (testName: string, success: boolean) => {
    setTestResults(prev => ({ ...prev, [testName]: success }));
  };

  // 测试 1: 连接到 WebSocket
  const testConnection = async () => {
    try {
      addLog('测试 1: 连接到 WebSocket...');
      await connect();
      addLog('✅ WebSocket 连接成功');
      updateTestResult('connection', true);
    } catch (err) {
      addLog(`❌ WebSocket 连接失败: ${err}`);
      updateTestResult('connection', false);
    }
  };

  // 测试 2: 初始化模型
  const testInitModel = async () => {
    try {
      addLog('测试 2: 初始化 NetPyNE 模型...');
      await initModel();
      addLog('✅ 模型初始化成功');
      updateTestResult('initModel', true);
    } catch (err) {
      addLog(`❌ 模型初始化失败: ${err}`);
      updateTestResult('initModel', false);
    }
  };

  // 测试 3: 获取网络数据
  const testGetNetwork = async () => {
    try {
      addLog('测试 3: 获取网络数据...');
      await getNetwork();
      addLog(`✅ 网络数据获取成功: ${networkData?.cells.length || 0} 个细胞`);
      updateTestResult('getNetwork', true);
    } catch (err) {
      addLog(`❌ 获取网络数据失败: ${err}`);
      updateTestResult('getNetwork', false);
    }
  };

  // 测试 4: 运行仿真
  const testRunSimulation = async () => {
    try {
      addLog('测试 4: 运行仿真...');
      await runSimulation();
      addLog('✅ 仿真运行完成');
      updateTestResult('runSimulation', true);
    } catch (err) {
      addLog(`❌ 仿真运行失败: ${err}`);
      updateTestResult('runSimulation', false);
    }
  };

  // 测试 5: 获取仿真数据
  const testGetSimulationData = async () => {
    try {
      addLog('测试 5: 获取仿真数据...');
      await getSimulationData();
      addLog(`✅ 仿真数据获取成功: ${simulationData?.spikes.length || 0} 个 spikes`);
      updateTestResult('getSimulationData', true);
    } catch (err) {
      addLog(`❌ 获取仿真数据失败: ${err}`);
      updateTestResult('getSimulationData', false);
    }
  };

  // 测试 6: 执行代码
  const testExecuteCode = async () => {
    try {
      addLog('测试 6: 执行 Python 代码...');
      const result = await executeCode('result = 2 + 2');
      addLog(`✅ 代码执行成功: ${result}`);
      updateTestResult('executeCode', true);
    } catch (err) {
      addLog(`❌ 代码执行失败: ${err}`);
      updateTestResult('executeCode', false);
    }
  };

  // 运行所有测试
  const runAllTests = async () => {
    setLogs([]);
    setTestResults({});
    
    addLog('========================================');
    addLog('开始运行完整测试流程');
    addLog('========================================');
    
    await testConnection();
    await new Promise(resolve => setTimeout(resolve, 500));
    
    await testInitModel();
    await new Promise(resolve => setTimeout(resolve, 500));
    
    await testGetNetwork();
    await new Promise(resolve => setTimeout(resolve, 500));
    
    await testRunSimulation();
    await new Promise(resolve => setTimeout(resolve, 500));
    
    await testGetSimulationData();
    await new Promise(resolve => setTimeout(resolve, 500));
    
    await testExecuteCode();
    
    addLog('========================================');
    addLog('测试流程完成');
    addLog('========================================');
  };

  // 计算测试通过率
  const passedTests = Object.values(testResults).filter(Boolean).length;
  const totalTests = Object.keys(testResults).length;
  const passRate = totalTests > 0 ? (passedTests / totalTests * 100).toFixed(0) : 0;

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h4" gutterBottom>
        Geppetto 前后端联调测试
      </Typography>

      {/* 连接状态 */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            连接状态
          </Typography>
          <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
            <Chip
              label={isConnected ? '已连接' : '未连接'}
              color={isConnected ? 'success' : 'default'}
            />
            {isConnecting && <CircularProgress size={20} />}
            {isSimulationRunning && (
              <Chip label="仿真运行中..." color="primary" />
            )}
          </Box>
          {error && (
            <Alert severity="error" sx={{ mt: 2 }}>
              {error}
            </Alert>
          )}
        </CardContent>
      </Card>

      {/* 测试控制 */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            测试控制
          </Typography>
          <Grid container spacing={2}>
            <Grid item>
              <Button
                variant="contained"
                color="primary"
                onClick={runAllTests}
                disabled={isConnecting || isSimulationRunning}
              >
                运行所有测试
              </Button>
            </Grid>
            <Grid item>
              <Button
                variant="outlined"
                onClick={testConnection}
                disabled={isConnecting}
              >
                测试连接
              </Button>
            </Grid>
            <Grid item>
              <Button
                variant="outlined"
                onClick={testInitModel}
                disabled={!isConnected}
              >
                初始化模型
              </Button>
            </Grid>
            <Grid item>
              <Button
                variant="outlined"
                onClick={testGetNetwork}
                disabled={!isConnected}
              >
                获取网络
              </Button>
            </Grid>
            <Grid item>
              <Button
                variant="outlined"
                onClick={testRunSimulation}
                disabled={!isConnected || isSimulationRunning}
              >
                运行仿真
              </Button>
            </Grid>
            <Grid item>
              <Button
                variant="outlined"
                onClick={testGetSimulationData}
                disabled={!isConnected}
              >
                获取数据
              </Button>
            </Grid>
            <Grid item>
              <Button
                variant="outlined"
                color="error"
                onClick={disconnect}
                disabled={!isConnected}
              >
                断开连接
              </Button>
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      <Grid container spacing={3}>
        {/* 测试结果 */}
        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                测试结果
              </Typography>
              {totalTests > 0 && (
                <Alert severity={passRate === '100' ? 'success' : 'warning'} sx={{ mb: 2 }}>
                  通过率: {passRate}% ({passedTests}/{totalTests})
                </Alert>
              )}
              <List dense>
                {Object.entries(testResults).map(([test, passed]) => (
                  <ListItem key={test}>
                    <ListItemText
                      primary={test}
                      secondary={passed ? '✅ 通过' : '❌ 失败'}
                    />
                  </ListItem>
                ))}
              </List>
            </CardContent>
          </Card>

          {/* 网络数据 */}
          {networkData && (
            <Card sx={{ mt: 3 }}>
              <CardContent>
                <Typography variant="h6" gutterBottom>
                  网络数据
                </Typography>
                <Typography variant="body2">
                  细胞数量: {networkData.cells.length}
                </Typography>
                <Typography variant="body2">
                  连接数量: {networkData.connections.length}
                </Typography>
                <Typography variant="body2">
                  种群数量: {networkData.populations.length}
                </Typography>
                <Divider sx={{ my: 2 }} />
                <Typography variant="subtitle2" gutterBottom>
                  种群详情:
                </Typography>
                {networkData.populations.map((pop, idx) => (
                  <Typography key={idx} variant="body2">
                    • {pop.name}: {pop.numCells} 个 {pop.cellType} 细胞
                  </Typography>
                ))}
              </CardContent>
            </Card>
          )}

          {/* 3D 可视化 */}
          {networkData && (
            <Card sx={{ mt: 3 }}>
              <CardContent>
                <Typography variant="h6" gutterBottom>
                  3D 可视化
                </Typography>
                <NetworkVisualization networkData={networkData} />
              </CardContent>
            </Card>
          )}

          {/* 仿真数据 */}
          {simulationData && (
            <Card sx={{ mt: 3 }}>
              <CardContent>
                <Typography variant="h6" gutterBottom>
                  仿真数据
                </Typography>
                <Typography variant="body2">
                  Spike 数量: {simulationData.spikes.length}
                </Typography>
                <Typography variant="body2">
                  Trace 数量: {Object.keys(simulationData.traces).length}
                </Typography>
                <Typography variant="body2">
                  LFP 数据点: {simulationData.lfp.length}
                </Typography>
              </CardContent>
            </Card>
          )}
        </Grid>

        {/* 日志 */}
        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                测试日志
              </Typography>
              <Paper
                sx={{
                  p: 2,
                  maxHeight: 600,
                  overflow: 'auto',
                  bgcolor: '#1e1e1e',
                  color: '#d4d4d4',
                  fontFamily: 'monospace',
                  fontSize: '0.875rem',
                }}
              >
                {logs.length === 0 ? (
                  <Typography variant="body2" color="text.secondary">
                    暂无日志
                  </Typography>
                ) : (
                  logs.map((log, idx) => (
                    <div key={idx}>{log}</div>
                  ))
                )}
              </Paper>
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Box>
  );
};

export default GeppettoTest;

